package com.xlkj.faces_input;

import android.Manifest;
import android.annotation.SuppressLint;
import android.app.ActionBar;
import android.app.Activity;
import android.app.admin.DevicePolicyManager;
import android.content.ComponentName;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.content.pm.PackageManager;
import android.graphics.Bitmap;
import android.graphics.Color;
import android.graphics.Point;
import android.graphics.Rect;
import android.graphics.drawable.BitmapDrawable;
import android.hardware.Camera;
import android.os.Build;
import android.os.Bundle;
import android.os.Environment;
import android.os.Handler;
import android.os.HandlerThread;
import android.os.Message;
import android.support.annotation.NonNull;
import android.support.v4.app.ActivityCompat;
import android.support.v4.content.PermissionChecker;
import android.util.Log;
import android.view.KeyEvent;
import android.view.SurfaceHolder;
import android.view.SurfaceView;
import android.view.View;
import android.view.WindowManager;
import android.widget.ImageView;
import android.widget.TextView;
import android.widget.Toast;

import com.iflytek.cloud.SpeechConstant;
import com.iflytek.cloud.SpeechSynthesizer;
import com.iflytek.cloud.SynthesizerListener;
import com.iflytek.cloud.util.ResourceUtil;
import com.lzy.okgo.OkGo;
import com.lzy.okgo.callback.StringCallback;
import com.lzy.okgo.model.Response;
import com.xlkj.listener.IflytekInitListenerImpl;
import com.xlkj.listener.IflytekSynthesizerListenerImpl;
import com.xlkj.okgo.FileDataBean;
import com.xlkj.okgo.JsonCallback;
import com.xlkj.receiver.AdminReceiver;
import com.xlkj.receiver.HomeReceiver;
import com.xlkj.tools.Utils;

import org.json.JSONException;
import org.json.JSONObject;

import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.File;
import java.io.FileOutputStream;
import java.io.FileWriter;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.Map;
import java.util.Timer;
import java.util.TimerTask;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.ThreadPoolExecutor;
import java.util.concurrent.locks.Lock;
import java.util.concurrent.locks.ReentrantLock;

import zeusees.tracking.Face;
import zeusees.tracking.FaceTracking;

import static com.xlkj.faces_input.ImgHelper.rotateYUV420Degree180;
import static com.xlkj.tools.GetMacAddress.getMacAddress;
import static com.xlkj.tools.Utils.decodeToBitMap;
import static com.xlkj.tools.Utils.rectExtend;
import static com.xlkj.tools.Utils.rotaingImageView;

public class MainActivity extends Activity {

    private String[] denied;
    private String[] permissions = {Manifest.permission.WRITE_EXTERNAL_STORAGE, Manifest.permission.CAMERA};

    private static FaceTracking multiTrack106_color = null;
    private boolean track106_color = false;

    String macAddress;
    private static final String TAG = "MainActivity";
    static String interUrl = "http://xlai.sxxlkj.com";
    //    static String interUrl = "120.24.85.198";
    private TextView user_name, text_check, user_end_data, sync_state;
    boolean chkEquipment = false; //false 检测未通过不能使用 true 可以

    private SpeechSynthesizer mTts;
    private SynthesizerListener mTtsListener = new IflytekSynthesizerListenerImpl(this);

    private ImageView picture;
    private static final int TEXT_CHECK = 1;
    private static final int USER_NAME = 2;
    private static final int SYNC_STATE = 3;
    private static final int PICTURE = 4;
    private static Map<Integer, Long> personCache = new ConcurrentHashMap<Integer, Long>();
    private static Map<Integer, String> sessionCache = new ConcurrentHashMap<Integer, String>();
    Long lastSpeakAndShowTime = new Date().getTime();
    long initTime = new Date().getTime();
    int timeLoop = 500;

    private HandlerThread handlerThread_color;
    private Handler handler_color;
    private byte[] Nv21Data_color;
    private CameraColorOverlap cameraColorOverlap;
    private final Object lockObj_color = new Object();
    private SurfaceView surfaceView_color;
    private EGLUtils eglUtils_color;
    private GLFrame frame_color;

    private GLFramebuffer mFramebuffer;
    private GLPoints mPoints;
    private GLBitmap mBitmap;
    private boolean relayOn = false;
    private double relayTime = System.currentTimeMillis();
    private static Bitmap tmpMap = null;
    private double pose_value = 100;
    long startTime = new Date().getTime();
    static{
        multiTrack106_color = new FaceTracking("/sdcard/ZeuseesFaceTracking/models");
    }
    ExecutorService executorService = Executors.newFixedThreadPool(6);
    ExecutorService executorSend = Executors.newFixedThreadPool(6);

    public void copyFilesFromAssets(Context context, String oldPath, String newPath) {
        try {
            String[] fileNames = context.getAssets().list(oldPath);

            if (fileNames.length > 0) {
                // directory
                File file = new File(newPath);
                if (!file.mkdir()) {
                    Log.d("mkdir", "can't make folder");
                }

                for (String fileName : fileNames) {
                    copyFilesFromAssets(context, oldPath + "/" + fileName,
                            newPath + "/" + fileName);
                }
            } else {
                // file
                InputStream is = context.getAssets().open(oldPath);
                FileOutputStream fos = new FileOutputStream(new File(newPath));
                byte[] buffer = new byte[1024];
                int byteCount;
                while ((byteCount = is.read(buffer)) != -1) {
                    fos.write(buffer, 0, byteCount);
                }
                fos.flush();
                is.close();
                fos.close();
            }
        } catch (Exception e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
    }

    void InitModelFiles() {
        String assetPath = "ZeuseesFaceTracking";
        String sdcardPath = Environment.getExternalStorageDirectory() + File.separator + assetPath;
        copyFilesFromAssets(MainActivity.this, assetPath, sdcardPath);
    }

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        setTheme(R.style.AppTheme);
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        setFullScreen();
        macAddress = getMacAddress(getApplicationContext());
        CheckMACAddress();

        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
            ArrayList<String> list = new ArrayList<>();
            for (int i = 0; i < permissions.length; i++) {
                if (PermissionChecker.checkSelfPermission(this, permissions[i]) == PackageManager.PERMISSION_DENIED) {
                    list.add(permissions[i]);
                }
            }
            if (list.size() != 0) {
                denied = new String[list.size()];
                for (int i = 0; i < list.size(); i++) {
                    denied[i] = list.get(i);
                }
                ActivityCompat.requestPermissions(this, denied, 5);
            } else {
                init_color();
            }
        } else {
            init_color();
        }

        // 初始化合成对象
        mTts = SpeechSynthesizer.createSynthesizer(this, new IflytekInitListenerImpl(this));
        setIflytekParam();

        user_name = findViewById(R.id.user_name);
        text_check = findViewById(R.id.text_check);
        user_end_data = findViewById(R.id.user_end_data);
        picture = findViewById(R.id.user_img);
        text_check.setText("");
        user_end_data.setText("客服电话：0351-3853826");
        user_name.setText("姓名：");
//        controlIO("ir","1");
//        controlIO("white_led","1");
//        controlIO("green_led","0");
//        controlIO("relay","0");
        executorService.submit(new ControlIO("white_led", "1"));
        executorService.submit(new ControlIO("green_led", "0"));
        executorService.submit(new ControlIO("relay", "0"));
    }

    @Override
    public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) {
        if (requestCode == 5) {
            boolean isDenied = false;
            for (int i = 0; i < denied.length; i++) {
                String permission = denied[i];
                for (int j = 0; j < permissions.length; j++) {
                    if (permissions[j].equals(permission)) {
                        if (grantResults[j] != PackageManager.PERMISSION_GRANTED) {
                            isDenied = true;
                            break;
                        }
                    }
                }
            }
            if (isDenied) {
                Toast.makeText(this, "请开启权限", Toast.LENGTH_SHORT).show();
            } else {
                init_color();
            }
        }
        super.onRequestPermissionsResult(requestCode, permissions, grantResults);
    }

    private void init_color() {
        InitModelFiles();
        cameraColorOverlap = new CameraColorOverlap(this);
        Nv21Data_color = new byte[CameraColorOverlap.PREVIEW_WIDTH * CameraColorOverlap.PREVIEW_HEIGHT * 2];
        mFramebuffer = new GLFramebuffer();
        frame_color = new GLFrame();
        mPoints = new GLPoints();
        mBitmap = new GLBitmap(this, R.mipmap.ic_launcher);
        handlerThread_color = new HandlerThread("DrawFacePointsThread");
        handlerThread_color.start();
        handler_color = new Handler(handlerThread_color.getLooper());
        cameraColorOverlap.setPreviewCallback(new Camera.PreviewCallback() {
            @Override
            public void onPreviewFrame(byte[] data, final Camera camera) {
                if (!chkEquipment) {
                    return;
                }

                Camera.Size previewSize = camera.getParameters().getPreviewSize();//获取尺寸,格式转换的时候要用到
                data = rotateYUV420Degree180(data, previewSize.width, previewSize.height);
                final Bitmap bitmap = rotaingImageView(270, decodeToBitMap(data, camera));

                synchronized (lockObj_color) {
                    System.arraycopy(data, 0, Nv21Data_color, 0, data.length);
                }
                handler_color.post(new Runnable() {
                    @Override
                    public void run() {
                        if (eglUtils_color == null) {
                            return;
                        }
                        frame_color.setS(100 / 100.0f);
                        frame_color.setH(0 / 360.0f);
                        frame_color.setL(100 / 100.0f - 1);

                        if (track106_color) {
                            multiTrack106_color.FaceTrackingInit(Nv21Data_color, CameraColorOverlap.PREVIEW_HEIGHT, CameraColorOverlap.PREVIEW_WIDTH);
                            track106_color = !track106_color;
                        } else {
                            multiTrack106_color.Update(Nv21Data_color, CameraColorOverlap.PREVIEW_HEIGHT, CameraColorOverlap.PREVIEW_WIDTH);
                        }
                        boolean rotate270 = cameraColorOverlap.getOrientation() == 270;

                        List<Face> faceActions = multiTrack106_color.getTrackingInfo();

//                        Log.i(TAG, "faceActions.size : "+faceActions.size());
                        /*if(faceActions.size()>0 && !lightStat ){
                            controlIO("white_led","1");
                            lightStat=true;
                            lightTime=System.currentTimeMillis();
                        }

                        if((System.currentTimeMillis()-lightTime>1000*10)&&lightStat && faceActions.size()==0){
                            controlIO("white_led","0");
                            lightStat=false;
                        }*/

//                        long time  = new Date().getTime() - startTime;
                        if (!user_name.getText().equals("姓名：") && new Date().getTime() - lastSpeakAndShowTime > 1000) {
                            Log.i(TAG, "chaixin : " + user_name.getText());
                            Bitmap user = ((BitmapDrawable) getResources().getDrawable(R.mipmap.user)).getBitmap();
                            Message message = new Message();
                            message.what = USER_NAME;
                            message.obj = "";
                            handler.sendMessage(message);
                            Message message1 = new Message();
                            message1.what = PICTURE;
                            message1.obj = user;
                            handler.sendMessage(message1);
                        }

                        if (new Date().getTime() - startTime > 60000 * 30) {
//                            rebootAction();
                        }
                        if ((System.currentTimeMillis() - relayTime > 1000 * 1) && relayOn) {
                            executorService.submit(new ControlIO("green_led", "0"));
                            executorService.submit(new ControlIO("relay", "0"));
                        }

                        float[] p = null;
                        float[] points = null;
                        for (Face r : faceActions) {
                            points = new float[106 * 2];
                            Rect face_rect = new Rect();
//                            Rect rect = new Rect(CameraColorOverlap.PREVIEW_HEIGHT - r.left,r.top,CameraColorOverlap.PREVIEW_HEIGHT - r.right,r.bottom);
                            int Xmax = 0, Xmin = 1000, Ymax = 0, Ymin = 1000;

                            Point[] point = new Point[5];

                            for (int i = 0; i < 106; i++) {
                                int x;
                                if (rotate270) {
                                    x = r.landmarks[i * 2];
                                } else {
                                    x = CameraColorOverlap.PREVIEW_HEIGHT - r.landmarks[i * 2];
                                }
                                int y = r.landmarks[i * 2 + 1];
                                if (Xmax < x) Xmax = x;
                                if (Ymax < y) Ymax = y;
                                if (Xmin > x) Xmin = x;
                                if (Ymin > y) Ymin = y;
                                points[i * 2] = view2openglX(x, CameraColorOverlap.PREVIEW_HEIGHT);
                                points[i * 2 + 1] = view2openglY(y, CameraColorOverlap.PREVIEW_WIDTH);
                                if (i == 43) point[0] = new Point(x, y);
                                if (i == 3) point[1] = new Point(x, y);
                                if (i == 69) point[2] = new Point(x, y);
                                if (i == 50) point[3] = new Point(x, y);
                                if (i == 45) point[4] = new Point(x, y);
                            }

                            Pose pose = poseEstimate(point);
                            rectExtend(bitmap, face_rect, 22);

                            if (faceActions.size() > 0) {
//                            pitch：表点头和昂头  yaw：侧脸正脸   roll：摇头
                                if (pose.getPitch() < 0.32 && pose.getRoll() < 38 && pose.getYaw() < 0.28) {
//                            if (true){
                                    Log.i(TAG, "正脸" + pose.toString());
                                    int face_width = Xmax - Xmin;
                                    Log.i(TAG, "face_width: " + face_width);
                                    int face_heigh = Ymax - Ymin;
                                    face_rect.left = Xmin > 0 ? Xmin / 2 : 0;
                                    face_rect.right = (Xmax / 2 < bitmap.getWidth()) ? Xmax / 2 : bitmap.getWidth();
                                    face_rect.bottom = (Ymax / 2 < bitmap.getHeight()) ? Ymax / 2 : bitmap.getHeight();
                                    face_rect.top = Ymin > 0 ? Ymin / 2 : 0;

//                                  Log.i(TAG, "face_rect:  left " +face_rect.left +",top "+ face_rect.top +",right "+ face_rect.right +",bottom "+ face_rect.bottom+"bitmap width"+bitmap.getWidth()+"bitmap height "+bitmap.getHeight());
                                    rectExtend(bitmap, face_rect, face_width, face_heigh);
//                                  Log.i(TAG, "face_rect 裁剪 :  left " +face_rect.left +",top "+ face_rect.top +",right "+ face_rect.right +",bottom "+ face_rect.bottom);
                                    double tmp_v = pose.getPitch() + pose.getYaw();
                                    if (pose_value > tmp_v) {
                                        pose_value = tmp_v;
                                        tmpMap = Utils.crop(bitmap, face_rect);
                                    }
                                    final int faceid = r.ID;
                                    long nowTime = new Date().getTime();
                                    if ((nowTime - initTime) >= timeLoop && tmpMap != null && face_width > 70) {
                                        final Bitmap face_bmp = tmpMap.copy(Bitmap.Config.ARGB_8888, true);

                                        executorSend.submit(new Send(face_bmp, faceid));
                                        int threadCount = ((ThreadPoolExecutor) executorSend).getActiveCount();
                                        Log.i(TAG, "2.threadCount====" + threadCount);

                                        initTime = nowTime;
                                        pose_value = 100;
                                        tmpMap = null;
                                    }
                                } else {
                                    Toast.makeText(MainActivity.this, "请正视屏幕", Toast.LENGTH_LONG).show();
                                }
                            }

                            if (p != null) {
                                break;
                            }
                        }
                        int tid = 0;
                        if (p != null) {
                            mBitmap.setPoints(p);
                            tid = mBitmap.drawFrame();
                        }
                        frame_color.drawFrame(tid, mFramebuffer.drawFrameBuffer(), mFramebuffer.getMatrix());
                        if (points != null) {
                            mPoints.setPoints(points);
                            mPoints.drawPoints();
                        }
                        eglUtils_color.swap();

                    }
                });
            }
        });
        surfaceView_color = findViewById(R.id.surfaceview_color);
        surfaceView_color.getHolder().addCallback(new SurfaceHolder.Callback() {
            @Override
            public void surfaceCreated(SurfaceHolder holder) {

            }

            @Override
            public void surfaceChanged(final SurfaceHolder holder, int format, final int width, final int height) {
                Log.d(TAG, "surfaceChanged");
                handler_color.post(new Runnable() {
                    @Override
                    public void run() {
                        if (eglUtils_color != null) {
                            eglUtils_color.release();
                        }
                        eglUtils_color = new EGLUtils();
                        eglUtils_color.initEGL(holder.getSurface());
                        mFramebuffer.initFramebuffer();
                        frame_color.initFrame();
                        frame_color.setSize(width, height, CameraColorOverlap.PREVIEW_HEIGHT, CameraColorOverlap.PREVIEW_WIDTH);
                        mPoints.initPoints();
                        mBitmap.initFrame(CameraColorOverlap.PREVIEW_HEIGHT, CameraColorOverlap.PREVIEW_WIDTH);
                        cameraColorOverlap.openCamera(mFramebuffer.getSurfaceTexture());
                    }
                });
            }

            @Override
            public void surfaceDestroyed(SurfaceHolder holder) {
                handler_color.post(new Runnable() {
                    @Override
                    public void run() {
                        cameraColorOverlap.release();
                        mFramebuffer.release();
                        frame_color.release();
                        mPoints.release();
                        mBitmap.release();
                        if (eglUtils_color != null) {
                            eglUtils_color.release();
                            eglUtils_color = null;
                        }
                    }
                });

            }
        });
        if (surfaceView_color.getHolder().getSurface() != null && surfaceView_color.getWidth() > 0) {
            handler_color.post(new Runnable() {
                @Override
                public void run() {
                    if (eglUtils_color != null) {
                        eglUtils_color.release();
                    }
                    eglUtils_color = new EGLUtils();
                    eglUtils_color.initEGL(surfaceView_color.getHolder().getSurface());
                    mFramebuffer.initFramebuffer();
                    frame_color.initFrame();
                    frame_color.setSize(surfaceView_color.getWidth(), surfaceView_color.getHeight(), CameraColorOverlap.PREVIEW_HEIGHT, CameraColorOverlap.PREVIEW_WIDTH);
                    mPoints.initPoints();
                    mBitmap.initFrame(CameraColorOverlap.PREVIEW_HEIGHT, CameraColorOverlap.PREVIEW_WIDTH);
                    cameraColorOverlap.openCamera(mFramebuffer.getSurfaceTexture());
                }
            });
        }
    }

    private float view2openglX(int x, int width) {
        float centerX = width / 2.0f;
        float t = x - centerX;
        return t / centerX;
    }

    private float view2openglY(int y, int height) {
        float centerY = height / 2.0f;
        float s = centerY - y;
        return s / centerY;
    }

    public static Pose poseEstimate(Point[] point) {
        Pose pose = new Pose();
        double dist_A = Math.sqrt((point[0].x - point[2].x) * (point[0].x - point[2].x)
                + (point[0].y - point[2].y) * (point[0].y - point[2].y));
        double dist_B = Math.sqrt((point[1].x - point[2].x) * (point[1].x - point[2].x)
                + (point[1].y - point[2].y) * (point[1].y - point[2].y));
        double dist_C = Math.sqrt((point[3].x - point[2].x) * (point[3].x - point[2].x)
                + (point[3].y - point[2].y) * (point[3].y - point[2].y));
        double dist_D = Math.sqrt((point[4].x - point[2].x) * (point[4].x - point[2].x)
                + (point[4].y - point[2].y) * (point[4].y - point[2].y));
        double high_rate = dist_A / dist_C;
        double width_rate = dist_C / dist_D;

        double high_ratio_variance = Math.abs(high_rate - 1.1);
        double width_ratio_variance = Math.abs(width_rate - 1);

        double dy = (point[1].y - point[0].y);
        double dx = (point[1].x - point[0].x);

        double angle = Math.atan2(dy, dx) * 180.0 / Math.PI;
//        Log.i(TAG,"angle:(摇头) " + angle);// 角度
//        Log.i(TAG,"high_ratio_variance :（点头） " + high_ratio_variance);// 比值
//        Log.i(TAG,"width_ratio_variance : （侧脸）" + width_ratio_variance);// 比值
        pose.setPitch(high_ratio_variance);
        pose.setYaw(width_ratio_variance);
        pose.setRoll(angle);
        return pose;
    }

    public class Send implements Runnable {
        private  Bitmap bitmap;
        private int faceid;

        public Send(Bitmap bitmap, int faceid){
            this.bitmap = bitmap;
            this.faceid = faceid;
        }

        @Override
        public void run() {
            try {
                    final long upfile_start = System.currentTimeMillis();
                    Lock lock = new ReentrantLock();
                    if (sessionCache.containsKey(faceid)) {
                        try {
                            lock.lock();
                            if ((new Date().getTime() - personCache.get(faceid)) < 2 * 1000) {
                                String face_name = sessionCache.get(faceid);
                                long time = System.currentTimeMillis() - upfile_start;
                                tips(bitmap, face_name, false);

                                Log.i(TAG, "*****已识别过 face_id:" + face_name + "_" + faceid + ", 时间：" + time);
                            } else {
                                sessionCache.clear();
                                personCache.clear();
                            }
                        } catch (Exception e) {
                            e.printStackTrace();
                        } finally {
                            lock.unlock();
                        }
                    } else {
                        final String p = Utils.saveBitmap(bitmap);
                        lock.lock();
                        final File upfile = new File(p);
            OkGo.<String>post(interUrl+"/workshop/face_recognition_file.htm?type=终端")
                    .tag(this)
                    .params("file", upfile)
                    .isMultipart(true)
                    .execute(new StringCallback() {
                        @Override
                        public void onSuccess(Response<String> response) {
                            if(text_check.getText().equals("网络连接失败")){
                                text_check.setText("");
                            }
                            upfile.delete();
                            Log.i(TAG, "response.body() : "+response.body());

                            try {
                                JSONObject jsonObject = new JSONObject(response.body());
                                String success = (String) jsonObject.get("success");
                                if(success.equals("true")){
                                    String name = (String) jsonObject.get("name");
                                    String [] text_i = name.split("_");

                                    if(text_i.length==3){
                                        String face_name = text_i[0];
                                        double score = Double.parseDouble(text_i[2]);
                                        tips(bitmap,face_name,true);
                                        if(score >= 0.61){
                                            sessionCache.put(faceid,face_name);
                                            personCache.put(faceid,new Date().getTime());
                                        }

                                        long time = System.currentTimeMillis()-upfile_start;
                                        Log.i(TAG, "!!!!!!未识别过 face_id:"+ face_name + "_" + faceid+", 时间："+time);
                                    }
                                }
                            } catch (JSONException e) {
                                e.printStackTrace();
                            }
                        }
                        @Override
                        public void onError(Response<String> response) {
                            upfile.delete();
                            text_check.setText("网络连接失败");
                        }
                    });
//                        OkGo.<FileDataBean>post("http://120.24.79.231:8989/recognize")
//                                .tag(this)
//                                .upFile(upfile)
//                                .execute(new JsonCallback<FileDataBean>(FileDataBean.class) {
//                                    @Override
//                                    public void onSuccess(Response<FileDataBean> response) {
//                                        if (text_check.getText().equals("网络连接失败")) {
//                                            text_check.setText("");
//                                        }
//
//                                        upfile.delete();
//                                        Log.i(TAG, "response.body() : " + response.body());
//
//                                        if (response.body() != null && response.body().getResult() != null && response.body().getResult().size() > 0) {
//                                            String text = response.body().getResult().get(0);
//                                            Log.i(TAG, "send: " + text);
//
//                                            String[] text_i = text.split("_");
//                                            if (text_i.length == 3) {
//                                                String face_name = text_i[0];
//                                                double score = Double.parseDouble(text_i[2]);
//
//                                                tips(bitmap, face_name, true);
//                                                if (score >= 0.61) {
//                                                    sessionCache.put(faceid, face_name);
//                                                    personCache.put(faceid, new Date().getTime());
//                                                }
//
//                                                long time = System.currentTimeMillis() - upfile_start;
//                                                Log.i(TAG, "!!!!!!未识别过 face_id:" + face_name + "_" + faceid + ", 时间：" + time);
//                                            }
//
//
//                                        }
//                                    }
//
//                                    @Override
//                                    public void onError(Response<FileDataBean> response) {
//                                        upfile.delete();
//                                        text_check.setText("网络连接失败");
//                                    }
//                                });

                        lock.unlock();
                    }
            }catch (Exception e) {
                e.printStackTrace();
            }
        }
    }

    private synchronized void tips(Bitmap bitmap, String facename, boolean pic) {
        if (new Date().getTime() - lastSpeakAndShowTime < 2000) {
            return;
        }
        try {
            if (pic) {
                Message message = new Message();
                message.what = PICTURE;
                message.obj = bitmap;
                handler.sendMessage(message);
            }

            Message message = new Message();
            message.what = USER_NAME;
            message.obj = facename;
            handler.sendMessage(message);
//            mTts.startSpeaking(facename, mTtsListener);

            if (!relayOn) {
                int threadCount = ((ThreadPoolExecutor) executorService).getActiveCount();
                Log.i(TAG, "1.threadCount====" + threadCount);

                executorService.submit(new ControlIO("green_led", "1"));
                executorService.submit(new ControlIO("relay", "1"));
            }
            relayTime = System.currentTimeMillis();
            lastSpeakAndShowTime = new Date().getTime();
        } catch (Exception e) {
            Log.e(TAG, "tips: " + e.getMessage());
        }
    }

    public class ControlIO implements Runnable {
        private String type;
        private String value;

        public ControlIO(String type, String value) {
            this.type = type;
            this.value = value;
        }

        @Override
        public void run() {
            setLedOnOff(type,value);
        }
    }

    private void setLedOnOff(String type, String value) {
        try {
            BufferedWriter bufWriter = null;
            bufWriter = new BufferedWriter(new FileWriter("/sys/class/custom_class/custom_dev/"+type));
            bufWriter.write(value + "");
            bufWriter.close();
            Log.d(TAG, "write setLedOnOff: " + value);
        } catch (IOException e) {
            Log.e(TAG,"erro= "+ Log.getStackTraceString(e));
        }finally {
            if (type == "green_led" && value == "1")
                relayOn = true;
            if (type == "green_led" && value == "0")
                relayOn = false;
        }
    }

    public void rebootAction() {
        new Thread(new Runnable() {
            @Override
            public void run() {
                try {
                    Process p = null;
                    try {
                        p = Runtime.getRuntime().exec("reboot");
                        p.waitFor();
                    } catch (Exception e) {
                        e.printStackTrace();
                    } finally {
                        if (p != null) {
                            p.destroy();
                        }
                    }
                } catch (Exception e) {
                    e.printStackTrace();
                }
            }
        }).start();
    }

    /**
     * UI线程 start
     **/
    @SuppressLint("HandlerLeak")
    private Handler handler = new Handler() {
        @SuppressLint("SetTextI18n")
        @Override
        public void handleMessage(Message msg) {
            switch (msg.what) {
                case TEXT_CHECK:
                    if (msg.arg1 == 0) {
                        text_check.setText("未检测到人脸");
                        text_check.setTextColor(Color.parseColor("#F44336"));
                    } else {
                        text_check.setText("已检测到人脸");
                        text_check.setTextColor(Color.parseColor("#4cd964"));
                    }
                    break;
                case USER_NAME:
                    user_name.setText("姓名：" + msg.obj);
//                    user_end_data.setText("有效期至："+user_end_data_);
                    break;
                case SYNC_STATE:
                    if (msg.arg1 == 0) {
                        sync_state.setText("云同步中...");
                    } else {
                        sync_state.setText("");
                    }
                    break;
                case PICTURE:
                    picture.setImageBitmap((Bitmap) msg.obj);
                    break;
                default:
                    break;
            }
        }
    };

    /**
     * 隐藏状态栏底部操作栏 start
     **/
    private void setFullScreen() {
        getWindow().setFlags(WindowManager.LayoutParams.FLAG_KEEP_SCREEN_ON, WindowManager.LayoutParams.FLAG_KEEP_SCREEN_ON);//设置不自动灭屏
        //隐藏状态栏，actionbar
        if (Build.VERSION.SDK_INT >= 21) {

            View decorView = getWindow().getDecorView();

            int option = View.INVISIBLE | View.SYSTEM_UI_FLAG_LAYOUT_FULLSCREEN
                    | View.SYSTEM_UI_FLAG_LAYOUT_HIDE_NAVIGATION | View.SYSTEM_UI_FLAG_HIDE_NAVIGATION;
            decorView.setSystemUiVisibility(option);

            decorView.setOnSystemUiVisibilityChangeListener(new View.OnSystemUiVisibilityChangeListener() {
                @Override
                public void onSystemUiVisibilityChange(int i) {
                    if (i == View.SYSTEM_UI_FLAG_FULLSCREEN || i == View.SYSTEM_UI_FLAG_LAYOUT_FULLSCREEN) {
                        Log.i("info", "全屏状态");
                    } else {
                        View decorView = getWindow().getDecorView();
                        int option = View.INVISIBLE | View.SYSTEM_UI_FLAG_LAYOUT_FULLSCREEN
                                | View.SYSTEM_UI_FLAG_LAYOUT_HIDE_NAVIGATION | View.SYSTEM_UI_FLAG_HIDE_NAVIGATION;
                        decorView.setSystemUiVisibility(option);
                    }
                }
            });

            getWindow().setStatusBarColor(Color.TRANSPARENT);
        }
        //隐藏actionbar
        ActionBar mActionBar = getActionBar();
        if (mActionBar != null) {
            mActionBar.hide();
        }
    }
    /**  隐藏状态栏底部操作栏 end **/

    /**
     * 检查该机MAC地址 start
     **/
    public void CheckMACAddress() {
        new Thread() {
            @Override
            public void run() {
                OkGo.<String>get(interUrl + "/workshop/menu/ai/equipment/check.htm?&macAddress=" + macAddress)
                        .tag(this)
                        .execute(new StringCallback() {
                            @Override
                            public void onSuccess(Response<String> response) {
                                String json = response.body();
                                if (response.body() != null) {
                                    try {
                                        final JSONObject jsonObject = new JSONObject(json);
                                        if ("success".equals(jsonObject.get("tip"))) {
                                            text_check.setText("");
                                            chkEquipment = true;
                                        } else if ("warning".equals(jsonObject.get("tip"))) {
                                            text_check.setText("");
                                            chkEquipment = true;
                                        } else {
                                            text_check.setText(jsonObject.get("msg").toString());

                                            TimerTask task = new TimerTask() {
                                                @Override
                                                public void run() {
                                                    CheckMACAddress();
                                                }
                                            };
                                            Timer timer = new Timer();
                                            timer.schedule(task, 5000);//3秒后执行TimeTask的run方法
                                        }
                                    } catch (Exception e) {
                                        e.printStackTrace();
                                    }
                                }
                            }

                            @Override
                            public void onError(Response<String> response) {
                                text_check.setText("网络连接失败");
                                TimerTask task = new TimerTask() {
                                    @Override
                                    public void run() {
                                        CheckMACAddress();
                                    }
                                };
                                Timer timer = new Timer();
                                timer.schedule(task, 5000);//3秒后执行TimeTask的run方法
                            }
                        });
            }
        }.start();
    }
    /** 检查该机MAC地址 end **/

    /**
     * 监听home/menu 使按键点击失效 start
     **/
    public void MonitorKey() {
        // 监听点击home/menu
        HomeReceiver homeReceiver = new HomeReceiver();
        IntentFilter intentFilter = new IntentFilter();
        intentFilter.addAction(Intent.ACTION_CLOSE_SYSTEM_DIALOGS);
        intentFilter.addAction(Intent.ACTION_SCREEN_ON);
        intentFilter.addAction(Intent.ACTION_SCREEN_OFF);
        intentFilter.addAction(Intent.ACTION_USER_PRESENT);
        registerReceiver(homeReceiver, intentFilter);

        ComponentName who = new ComponentName(this, AdminReceiver.class);
        Intent i = new Intent(DevicePolicyManager.ACTION_ADD_DEVICE_ADMIN);
        i.putExtra(DevicePolicyManager.EXTRA_DEVICE_ADMIN, who);
        i.putExtra(DevicePolicyManager.EXTRA_ADD_EXPLANATION, "激活锁频功能");
        startActivityForResult(i, 0);
    }

    @Override
    public boolean onKeyDown(int keyCode, KeyEvent event) {
        //屏蔽返回
        if (keyCode == KeyEvent.KEYCODE_BACK) {
            return true;
            //home和menu无效
        } else if (keyCode == KeyEvent.KEYCODE_HOME) {
            Log.i(TAG, "in-home");
            return true;
        } else if (keyCode == KeyEvent.KEYCODE_MENU) {
            Log.i(TAG, "in-menu");
            return true;
        }
        return super.onKeyDown(keyCode, event);
    }
    /** 监听home/menu 使按键点击失效 end **/

    /**** 科大讯飞语音合成 start ****/
    /**
     * 参数设置
     *
     * @return
     */
    private void setIflytekParam() {
        // 清空参数
        mTts.setParameter(SpeechConstant.PARAMS, null);
        //设置合成

        //设置使用本地引擎
        mTts.setParameter(SpeechConstant.ENGINE_TYPE, SpeechConstant.TYPE_LOCAL);
        //设置发音人资源路径
        mTts.setParameter(ResourceUtil.TTS_RES_PATH, getResourcePath());
        //设置发音人
//        mTts.setParameter(SpeechConstant.VOICE_NAME,voicerLocal);

        //设置合成语速
        mTts.setParameter(SpeechConstant.SPEED, "50");
        //设置合成音调
        mTts.setParameter(SpeechConstant.PITCH, "50");
        //设置合成音量
        mTts.setParameter(SpeechConstant.VOLUME, "50");
        //设置播放器音频流类型
        mTts.setParameter(SpeechConstant.STREAM_TYPE, "3");

        // 设置播放合成音频打断音乐播放，默认为true
        mTts.setParameter(SpeechConstant.KEY_REQUEST_FOCUS, "true");

        // 设置音频保存路径，保存音频格式支持pcm、wav，设置路径为sd卡请注意WRITE_EXTERNAL_STORAGE权限
        // 注：AUDIO_FORMAT参数语记需要更新版本才能生效
        mTts.setParameter(SpeechConstant.AUDIO_FORMAT, "wav");
        mTts.setParameter(SpeechConstant.TTS_AUDIO_PATH, Environment.getExternalStorageDirectory() + "/msc/tts.wav");
    }

    /**
     * 获取语音文件路径
     *
     * @return
     */
    private String getResourcePath() {
        StringBuffer tempBuffer = new StringBuffer();
        //合成通用资源
        tempBuffer.append(ResourceUtil.generateResourcePath(this, ResourceUtil.RESOURCE_TYPE.assets, "tts/common.jet"));
        tempBuffer.append(";");
        //发音人资源
        tempBuffer.append(ResourceUtil.generateResourcePath(this, ResourceUtil.RESOURCE_TYPE.assets, "tts/xiaoyan.jet"));
        return tempBuffer.toString();
    }

    /**** 科大讯飞语音合成 end ****/
}